<script setup>
import { useRouter } from 'vue-router';
import axios from 'axios';
axios.defaults.baseURL = 'http://127.0.0.1:8100/api';
const router = useRouter();
// 设置全局的登录方式标志
let loginMethod = ref("password");
// -----------------------------------------------
// 监听滚轮实现导航栏样式变化
// -----------------------------------------------
onMounted(() => {
  window.addEventListener("scroll", scrolling);
});
onUnmounted(() => {
  window.removeEventListener("scroll", scrolling);
});
let scroll = ref(0);
const scrolling = () => {
  scroll.value = document.documentElement.scrollTop;
};
watch(
  scroll,
  (newVal) => {
    if (newVal == 0) {
      document.getElementById("navi").classList.remove("navigation")
      document.getElementById("navi").classList.add("navigation1")
    } else {
      document.getElementById("navi").classList.add("navigation")
      document.getElementById("navi").classList.remove("navigation1")
    }
  }
);

// -----------------------------------------------
// 登录消息窗
// -----------------------------------------------
let dialogVisible = ref(false)

// -----------------------------------------------
// 登录方式样式切换
// -----------------------------------------------
//切换眼睛图标
let eye_icon_class = ref("pwd-img")
let pwd_input_type = ref("password")

function eye_chage(){
  if(eye_icon_class.value == "pwd-img"){
    eye_icon_class.value = "pwd-img-sel"
    pwd_input_type.value = "text"
  }else{
    eye_icon_class.value = "pwd-img"
    pwd_input_type.value = "password"
  }
}

//标题切换
let login_acc_class = ref("title-class-selected")
let login_pho_class = ref("title-class")
let acc_class = ref("acc-input")
let pwd_class = ref("pwd-input")
let code_class = ref("acc-input hide")
let phone_class = ref("phone-input hide")
let getcode_class = ref("code-disabled hide")
let text_acc_class = ref("")
let text_pwd_class = ref("")
let text_phone_class = ref("hide")
let text_code_class = ref("hide")

function title_change(e){
  if(e.target.id == "phone-login"){
    loginMethod.value = "sms";
    login_pho_class.value = "title-class-selected"
    login_acc_class.value = "title-class"

    acc_class.value = "acc-input hide"
    pwd_class.value = "pwd-input hide"
    code_class.value = "acc-input"
    phone_class.value = "phone-input"
    getcode_class.value = "code-disabled"
    text_acc_class.value = "hide"
    text_pwd_class.value = "hide"
    text_phone_class.value = ""
    text_code_class.value = ""
    eye_icon_class.value = "pwd-img hide"

  }
  if(e.target.id == "acc-login"){
    login_acc_class.value = "title-class-selected"
    login_pho_class.value = "title-class"
    
    acc_class.value = "acc-input"
    pwd_class.value = "pwd-input"
    code_class.value = "acc-input hide"
    phone_class.value = "phone-input hide"
    getcode_class.value = "code-disabled hide"
    text_acc_class.value = ""
    text_pwd_class.value = ""
    text_phone_class.value = "hide"
    text_code_class.value = "hide"
    eye_icon_class.value = "pwd-img"
  }
}

// -----------------------------------------------
// 登录注册事件
// -----------------------------------------------
//手机号校验
let username = ref("")
let password = ref("")
let number = ref('')
let code = ref("")
let regex = /1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}/
watch(
  number,(newVal)=>{
    if(regex.test(number.value)){
      getcode_class.value = "code"
    }else{
      getcode_class.value = "code-disabled"
    }
  }
)

//注册按钮方法
function register(){
  router.push(`/reg`);
}

//登录按钮方法
async function loginByPwd(username, password) {
  try {
    // 发送 POST 请求到 /api/pwdLogin
    const response = await axios.post('/pwdLogin', {
      username: username,
      password: password
    });

    // 检查响应中的 msg 字段
    const msg = response.data.data?.msg;
    if (msg === "登录成功") {
      // 获取并存储 token 到 localStorage
      const token = response.data.data?.token;
      if (token) {
        localStorage.setItem('authToken', token);
        alert('登录成功 ');
        router.push(`/main`);
      } else {
        console.error('登录成功，但未接收到 token');
      }
    } else {
      console.error('登录失败:', msg || '未知错误');
      alert(msg || '登录失败，请重试');
    }
  } catch (error) {
    console.error('请求失败:', error);
    alert('登录请求失败，请稍后再试');
  }
}



// 短信验证码登录方法
async function loginByTel(number, code) {
  try {
    const response = await axios.post("/telLogin", { phoneNumber: number, code });
    const msg = response.data.data?.msg;
    if (msg === "登录成功") {
      const token = response.data.data?.token;
      if (token) {
        localStorage.setItem("authToken", token);
        alert("登录成功");
        router.push(`/main`);
      } else {
        console.error("登录成功，但未接收到 token");
      }
    } else {
      console.error("登录失败:", msg || "未知错误");
      alert(msg || "登录失败，请重试");
    }
  } catch (error) {
    console.error("请求失败:", error);
    alert("登录请求失败，请稍后再试");
  }
}



// 获取验证码方法
async function sendCode() {
  try {
    const params = new URLSearchParams();
    params.append("phoneNumber", number.value);  // 将手机号添加到表单参数中
    const response = await axios.post("/sendCode", params, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" }  // 设置表单编码类型
    });
    alert("验证码已发送，请检查您的手机");
  } catch (error) {
    console.error("发送验证码失败:", error);
    alert("验证码发送失败，请稍后再试");
  }
}


</script>

<template>
  <div>
    <header id="navi" class="navigation1">
      <img id="logo_img" class="logo_img" src="../assets/img/index/logo.png">
      <span class="logo_text">锐智CloudSync</span>
    </header>
    <div class="container_1">
      <div class="title_box">
        <div class="title">记录每一份热爱</div>
        <div class="title">让美好永远陪伴</div>
        <div class="info">为你电脑/手机中的文件提供云备份、预览、分享等服务，帮你更便捷安全地管理数据。</div>
        <button class="to_login_btn" @click="dialogVisible = true">去登陆</button>
      </div>
      <div class="img_box"></div>
    </div>
    <div class="container_2">
      <div class="title_1">数据管理</div>
      <div class="subtitle_1">不止存储，数据管理更便捷</div>

      <el-carousel style="width: 1000px;" height="350px" direction="vertical" :autoplay="true">
        <el-carousel-item>
          <div class="title_box_1">
            <div class="title_box_left">
              <div class="black_title_1">智能搜索，盘中文件一搜即有</div>
              <div class="gray_title_1">支持智能标题搜索、图片类型搜索、图片内文字搜索，轻轻松松搜你想要</div>
            </div>
            <img class="img_box_1" src="https://nd-static.bdstatic.com/m-static/wp-brand/img/search.76ec7250.png">
          </div>
        </el-carousel-item>
        <el-carousel-item>
          <div class="title_box_1">
            <div class="title_box_left">
              <div class="black_title_1">智能相册，<br />串联生活点滴中的小确幸</div>
              <div class="gray_title_1">智能分类让相册整理更加轻松，智能故事视频点亮回忆瞬间，智能配文让盘中相册会说话</div>
            </div>
            <img class="img_box_1" src="https://nd-static.bdstatic.com/m-static/wp-brand/img/photo.dd6fc760.png">
          </div>
        </el-carousel-item>
        <el-carousel-item>
          <div class="title_box_1">
            <div class="title_box_left">
              <div class="black_title_1">智同步空间，文件实时同步</div>
              <div class="gray_title_1">空间文件多端自动同步，历史版本恢复无忧，随时随地高效办公</div>
            </div>
            <img class="img_box_1" src="https://nd-static.bdstatic.com/m-static/wp-brand/img/sync.57eadcb5.png">
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="footer">
      <div class="friendship">
        <span>商务合作</span>
        <span class="vline"></span>
        <span>隐私政策</span>
        <span class="vline"></span>
        <span>服务协议</span>
        <span class="vline"></span>
        <span>权利声明</span>
        <span class="vline"></span>
        <span>版本更新</span>
        <span class="vline"></span>
        <span>版权投诉</span>
        <span class="vline"></span>
        <span>网盘认证</span>
      </div>
      <div class="friendship">
        <span class="gray_span">
          丁真网安备1145141919810号
        </span>
        <span class="gray_span">
          京ICP备2020042663号
        </span>
        <span class="gray_span">
          京网文[2024]2102-100号
        </span>
        <span class="gray_span">
          ©2024 Clouddisk
        </span>
      </div>
    </div>
    <el-dialog
    v-model="dialogVisible"
    width="600"
    class="dialog"
  >
  <div class="title-box">
                        <div class="title"><a @click="title_change($event)" :class="login_acc_class" id="acc-login"
                                href="javascript:void(0);">密码登录</a>
                        </div>
                        <div class="title" style="border-right: 0px;"><a @click="title_change($event)" :class="login_pho_class" id="phone-login"
                                href="javascript:void(0);">短信登录</a>
                        </div>
                    </div>
                    <div class="form-box">
                        <form>
                            <div class="input-box">
                                <div class="input1">
                                    <span :class="text_acc_class" id="text-acc">账号 </span><input v-model="username" placeholder="请输入账号" id="acc" :class="acc_class" type="text">
                                    <span id="text-phone" :class="text_phone_class">手机号 </span><input v-model="number" placeholder="请输入手机号" id="phone" :class="phone_class" type="text" >
                                    <a id="getcode" :class="getcode_class" @click="sendCode" >获取验证码</a>
                                </div>
                                <div class="input2">
                                    <span :class="text_pwd_class" id="text-pwd">密码 </span><input v-model="password" placeholder="请输入密码" id="pwd" :class="
                                    pwd_class" :type="pwd_input_type">
                                    <div id="eye-icon" @click="eye_chage"  :class="eye_icon_class"></div>
                                    <!-- <span id="text-code" :class="text_code_class" @click="sendCode">验证码 </span> -->
                                    <input v-model="code" placeholder="请输入验证码" id="code" :class="code_class" type="text">
                                </div>
                                <div id="message-box" class="message hide-fake"><span id="message"></span></div>
                            </div>
                            
                            <div class="form-btn">
                                <button id="regist" type="button" class="regist" @click="register">注册</button>
                                <button id="login"  type="button" class="login" @click="loginMethod === 'password' ? loginByPwd(username, password) : loginByTel(number, code)">登录</button>
                            </div>
                        </form>
                    </div>
    <template #footer>
      <div class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogVisible = false"></el-button> -->
        
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<style scoped>
@import "../assets/css/index.css";


.el-carousel__indicator--vertical .el-carousel__button {
  height: 20px;
  width: 4px;
}

.el-carousel__button {
  background-color: blue;
}
</style>